package dao.server;

import java.io.StringWriter;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ProjectUtility {
	public static StringWriter getAllProject(DAO dao, DocumentBuilder docBuilder){
		ArrayList<Project> projectList = getAll(dao);
		StringWriter result;
		if(projectList != null && projectList.size() != 0){
			result = objectToXml(docBuilder, projectList);
			if(result != null){
				return result;
			}
			return null;
		}
		return null;
	}
	private static ArrayList<Project> getAll(DAO dao){
		if(dao != null)
			return dao.getAllProject();
		else
			return null;
	}
	private static StringWriter objectToXml(DocumentBuilder docBuilder,ArrayList<Project> projectList){
		try {
			// document elements
			Document doc = docBuilder.newDocument();
			Element document = doc.createElement("document");
			doc.appendChild(document);

			// set attribute to document element
			Attr type = doc.createAttribute("type");
			type.setValue("PROJECT");
			document.setAttributeNode(type);
			
			Attr action = doc.createAttribute("action");
			action.setValue("GET_ALL");
			document.setAttributeNode(action);

			// head elements
			Element head = doc.createElement("head");
			document.appendChild(head);

			// body elements
			Element body = doc.createElement("body");
			document.appendChild(body);
					
			for (Project p : projectList) {
				// project elements
				Element project = doc.createElement("project");
				body.appendChild(project);
				
				// id elements
				Element id = doc.createElement("id");
				id.appendChild(doc.createTextNode(String.valueOf(p.getId())));
				project.appendChild(id);

				// name elements
				Element name = doc.createElement("name");
				name.appendChild(doc.createTextNode(p.getName()));
				project.appendChild(name);

				// time elements
				Element time = doc.createElement("time");
				time.appendChild(doc.createTextNode(p.getTime()));
				project.appendChild(time);

			}

			// write the content into xml file
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(doc);
			StringWriter sw = new StringWriter();
			StreamResult result = new StreamResult(sw);
			transformer.transform(source, result);
			return sw;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
